<template>
  <div class="gstc-wrapper" ref="gstcElement"></div>
</template>
  <script setup lang="ts">
import { post } from '@/api/http'
import { Message } from '@arco-design/web-vue'
//甘特图插件
import GSTC from 'gantt-schedule-timeline-calendar/dist/gstc.wasm.esm.min.js'
import { Plugin as TimelinePointer } from 'gantt-schedule-timeline-calendar/dist/plugins/timeline-pointer.esm.min.js'
import { Plugin as Selection } from 'gantt-schedule-timeline-calendar/dist/plugins/selection.esm.min.js'
import { Plugin as ItemResizing } from 'gantt-schedule-timeline-calendar/dist/plugins/item-resizing.esm.min.js'
import { Plugin as ItemMovement } from 'gantt-schedule-timeline-calendar/dist/plugins/item-movement.esm.min.js'
import { Plugin as Bookmarks } from 'gantt-schedule-timeline-calendar/dist/plugins/time-bookmarks.esm.min.js'
import 'gantt-schedule-timeline-calendar/dist/style.css'
//引入中文版日期
import locale from './ch-cn'
const gstcElement = ref<any>('')
let gstc: any
let state: any
const emits = defineEmits(['rightGanttChart', 'sateMounted', 'drag'])

onMounted(() => {
  getSate()
})
const getSate = () => {
  /**
   * @type { import("gantt-schedule-timeline-calendar").Config }
   */
  nextTick(() => {
    GSTC.cA = () => false
    state = GSTC.api.stateFromConfig(config.value)
    globalThis.state = state
    gstc = GSTC({
      element: gstcElement.value,
      state,
    })
    globalThis.gstc = gstc
    emits('sateMounted', state, gstc)
  })
}

// ts写法
interface GanttChart {
  //   gtttRows: any
  //   gtttItems: any
  startTime: any
  endTime: any
  size: any
}
const props = withDefaults(
  defineProps<{
    configGanttChart: GanttChart | any
  }>(),
  {
    configGanttChart: {
      //   gtttRows: {},
      //   gtttItems: {},
      startTime: '',
      endTime: '',
      size: '',
    },
  }
)
const oldTaskIds = ref<any>([])
const itemResizingOptions = {
  events: {
    onStart({ items }: any) {
      return filterFrozenItems(items.after)
    },
    onResize({ items }: any) {
      return filterFrozenItems(items.after)
    },
    onEnd({ items }: any) {
      oldTaskIds.value.push(items.after[0].id)
      return filterFrozenItems(items.after)
    },
  },
}
const filterFrozenItems = (items: any) => {
  return items.filter((item: any) => {
    if (!item.frozen) return false
    return true
  })
}
let canChangeRow = true
let canCollide = true
function isCollision(item: any) {
  const allItems = gstc.api.getAllItems()
  for (const itemId in allItems) {
    if (itemId === item.id) continue
    const currentItem = allItems[itemId]
    if (currentItem.rowId === item.rowId) {
      if (item.time.start >= currentItem.time.start && item.time.start <= currentItem.time.end)
        return true
      if (item.time.end >= currentItem.time.start && item.time.end <= currentItem.time.end)
        return true
      if (item.time.start <= currentItem.time.start && item.time.end >= currentItem.time.end)
        return true
      if (item.time.start >= currentItem.time.start && item.time.end <= currentItem.time.end)
        return true
    }
  }
  return false
}
const itemMovementOptions = {
  events: {
    onMove({ items }: any) {
      console.log(items)
      return items.before.map((beforeMovementItem: any, index: any) => {
        // console.log(beforeMovementItem.rowId.split('gstcid-')[1])
        // console.log(beforeMovementItem.list.machineCode)
        if (items.before[index].rowId.split('gstcid-')[1] == items.after[index].rowId.split('gstcid-')[1]) {
          return items.initial[index]
        }
        if (beforeMovementItem.drag === false) {
          return items.initial[index]
        }
        const afterMovementItem = items.after[index]
        const myItem: any = GSTC.api.merge({}, afterMovementItem)

        if (!canChangeRow) {
          myItem.rowId = beforeMovementItem.rowId
        }
        if (!canCollide && isCollision(myItem)) {
          myItem.time = { ...beforeMovementItem.time }
          myItem.rowId = beforeMovementItem.rowId
        }
        oldTaskIds.value.push(myItem.id)
        dragAntiShake(items)
        return myItem
      })
    },
  },
}
//拖动防抖
let timer = ref<any>(null)
const dragAntiShake = (items: any) => {
  if (timer.value) clearTimeout(timer.value)
  timer.value = setTimeout(() => {
    let rowId = items.before[0].rowId
    let rowId1 = items.initial[0].rowId
    let Items = Object.values(gstc.api.getAllItems())
    let pam = {
      CurrentTask: items.before[0].list,
      MachineTask: Items.filter((item: any) => {
        return item.rowId == rowId
      }).sort((a: any, b: any) => Number(a.time.start) - Number(b.time.start)),
      OriginalMachineTask: Items.filter((item: any) => {
        // console.log(item.rowId)
        return item.rowId == rowId1
      }).sort((a: any, b: any) => Number(a.time.start) - Number(b.time.start)),
    }
    pam.CurrentTask.newMachineCode = items.before[0].rowId.split('gstcid-')[1]
    // console.log(pam)
    // console.log(GSTC.api.GSTCID('0'))
    emits('drag', pam)
    // pam.MachineTask.map((item: any) => {
    //   console.log(item.id)
    //   state.update(`config.chart.items.${item.id}`, (row: any) => {
    //     console.log(row)
    //     row.label = 'Changed dynamically'
    //     return row
    //   })
    // })
  }, 500)
}
const setTippyContent = (element: any, data: any) => {
  if (!gstc) return
  if ((!data || !data.item) && element._tippy) return element._tippy.destroy()
  const itemData = gstc.api.getItemData(data.item.id)
  if (!itemData) return element._tippy.destroy()
  if (itemData.detached && element._tippy) return element._tippy.destroy()
  // @ts-ignore
  if (!itemData.detached && !element._tippy) tippy(element, { trigger: 'mouseenter click' })
  if (!element._tippy) return
  const { startDate, endDate } = itemData.time
  const tooltipContent = `
  <ul>
      <li> 机台号：${data.row.label}</li>
      <li> 开始时间：${startDate.format('YYYY-MM-DD HH:mm')}</li>
      <li> 结束时间：${endDate.format('YYYY-MM-DD HH:mm ')}</li>
      <li> 重量：${data.item.label}</li>
      <li> 生产单号：${data.item.list.weaveingCode}</li>
      <li> 织布单号：${data.item.list.planOrderCode}</li>
      <li> 坯布名称：${data.item.list.greyName}</li>
    </ul> 
  `
  let bodyHtml = new DOMParser().parseFromString(tooltipContent, 'text/html').body
  bodyHtml.style.height = '100%'
  element._tippy.setContent(bodyHtml)
  // element._tippy.setContent(new DOMParser().parseFromString(tooltipContent, 'text/html').body)
}

const config = ref({
  licenseKey:
    '====BEGIN LICENSE KEY====\npY17i5maHimI8AVXW9ZydCo+SZaffA58dqSIMkidbhClOqFbpSYfpdZujkhFEIbaaLVnLh9ajmcH7ucc+Suvu76KIEgPvX82sWJHl5foSs+X5powgmWq0U0j2nQxFGNkv8PPsH0FLJ73I23hW1NNXGEyvHmAwUC6LmTKwcaw2Zo67csFTR4+KLf+6DNfHpWeFFYmljtasq5tFcCazLcvC6y54JvzTQtB6pweIZxoinv/8re6dx3uSIWSyuvxMkT/FtMyz7m48ErvaBLDdWu7Q/yjEyo8+kHwejKAs4p1dq5fG0R26NttuRv+AXlWEVWjzUcw6hFzhAhpRx80rKs4JA==||U2FsdGVkX18E6M/UefZ43ZgybReddxfEZ6nUZDYQMnN7YMiIa7kHYxbWsQmX9KnGX+ZUuNheLHwNrAAqr5JA6j+DBQa8QuwaRiysQq8mpx0=\nXLFXZnWnIDaSSgK5eU52/3OUhT0qfKez4fJ6hRuLsObmvVkQQEWlxvcU3UNrnGMMNSXMBIJCFZfc75RctO6W2xREjUhWnNGuiFywmEcp4pULaMx5FMsdAQ5lmpicuNrzeguAE70ug6+uq119yktmgPuNFK6U7DqM9t6bAcm4dSv/bJYZFxK7IRg6BL5wyVtNROsUCYKKvGTs3NvJear3hvWJToWcT6DIzTA/gdEb/FBOAjY3Sz0qLfaOhUekSqri5cnMOfTvz6G8Fpt2Y+e6jMa2y17OQIZvAjzD7oJLWgybQiGAXKhyv26vo8TKEQsiIsKD+NREI3hzLERXdLLQlQ==\n====END LICENSE KEY====',
  plugins: [
    TimelinePointer(),
    Selection(),
    ItemResizing(itemResizingOptions),
    ItemMovement(itemMovementOptions),
    Bookmarks(),
  ],
  innerHeight: 550,
  list: {
    columns: {
      data: {
        [GSTC.api.GSTCID('label')]: {
          id: GSTC.api.GSTCID('label'),
          width: 200,
          data: 'label',
          header: {
            content: '机台号',
          },
        },
      },
    },
    rows: {},
  },
  locale,
  chart: {
    time: {
      from: props.configGanttChart.startTime,
      to: props.configGanttChart.endTime,
      zoom: props.configGanttChart.size,
    },
    items: {},
  },
  actions: {
    'chart-timeline-items-row-item': [
      (element: any, data: any) => {
        // console.log(data)
        setTippyContent(element, data)
        const onClick = (e: any) => {
          e.preventDefault()
          //   visibleModify.value = true
          //   rightClickData.value = data.item
          emits('rightGanttChart', data.item)
          return false
        }
        element.addEventListener('contextmenu', onClick)
        return {
          update(element: any, newData: any) {
            data = newData
            setTippyContent(element, data)
          },
          destroy(element: any, data: any) {
            element.removeEventListener('click', onClick)
            if (element._tippy) element._tippy.destroy()
          },
        }
      },
    ],
  },
})
// 对外暴露的属性
defineExpose({
  oldTaskIds,
})
</script>
  <style scoped>
.gstc-wrapper {
  width: 100%;
  height: 100%;
}
:deep(.gstc__chart-calendar) {
  background: #5191fd;
}
:deep(.gstc__chart-timeline-grid-row-cell) {
  border-right: 1px solid #909090;
  border-bottom: 1px solid #909090;
  width: 40.2px !important;
}
:deep(.tippy-box) {
  border: 1px solid #333;
  color: #000;
  background-color: #fff;
}
:deep(.gstc__chart-calendar-date-content.gstc-date-medium) {
  color: #000;
  /* font-weight: 600; */
}
:deep(.gstc__list-column-header-resizer) {
  justify-content: center;
  color: #fff;
  background: #5191fd;
  width: 60px !important;
  border-right: 1px solid #bdbcbc;
}
:deep(.gstc__list-column-header-content) {
  width: 60px !important;
}
:deep(.gstc__list-column-rows) {
  width: 60px !important;
}
:deep(.gstc__list-column-rows-offset) {
  width: 60px !important;
}
:deep(.gstc__list-column-row-content) {
  width: 60px !important;
}
:deep(.gstc__list-column) {
  width: 60px !important;
}
:deep(.gstc__list-column-row-content) {
  text-align: center;
}
:deep(
    .gstc__chart-calendar-date--day,
    .gstc__chart-calendar-date--week,
    .gstc__chart-calendar-date--minute
  ) {
  font-size: 12px !important;
  width: 40.2px !important;
  color: #fff;
}
:deep(
    .gstc__chart-calendar-date-content--day,
    .gstc__chart-calendar-date-content--week,
    .gstc__chart-calendar-date-content--minute
  ) {
  font-size: 12px !important;
}
:deep(.gstc__chart-calendar-date--non-main-date .gstc__chart-calendar-date-content) {
  color: #fff;
}
:deep(.gstc__list-column-row) {
  border-bottom: 1px solid #909090;
  border-right: 1px solid #bdbcbc;
  width: 60px !important;

  /* border-top: 1px solid #909090; */
}
:deep(.gstc__list-column-header-resizer-dots) {
  display: none;
}
</style>